﻿var CIB = CIB || {};

CIB.EditMenu = function (DOMElementId) {
    DOMElementId = DOMElementId || "sideNavBox";

    _self = this;
    _self.PageLists = {};
    _self.ListsCount = 0;

    FillPageLists = function () {
        var WebsNLists = {};
        var currentUrl = window.location.protocol + "//" + window.location.hostname;

        try {
            if (typeof (_spWebPartComponents)) {
                for (var component in _spWebPartComponents) {
                    var WebPart = _spWebPartComponents[component];
                    if (WebPart) {
                        var strViewId = WebPart.storageId;
                        strViewId = strViewId.toUpperCase();

                        if (g_ViewIdToViewCounterMap) {
                            var ctxNum = g_ViewIdToViewCounterMap["{" + strViewId + "}"];
                            if (ctxNum) {
                                var ctxT = window["ctx" + ctxNum];
                                if (ctxT) {


                                    var WebUrl = ctxT.HttpRoot.replace(currentUrl, "");


                                    var ListId = ctxT.listName;

                                    var WebOj = WebsNLists[WebUrl];
                                    if (!WebOj) {
                                        WebsNLists[WebUrl] = [];
                                        WebOj = WebsNLists[WebUrl];
                                    }
                                    WebOj.push(ListId);
                                    _self.ListsCount++;
                                }
                            }
                        }
                    }
                }
            }
        } catch (e) {

        }

        if (_spPageContextInfo.pageListId) {
            var WebUrl = _spPageContextInfo.webAbsoluteUrl.replace(currentUrl, "");
            if (!WebsNLists[WebUrl])
                WebsNLists[WebUrl] = [];

            var id = _spPageContextInfo.pageListId.toUpperCase();

            var exists = false;
            for (var j = 0; j < WebsNLists[WebUrl].length; j++) {
                if (WebsNLists[WebUrl] == id) {
                    exists = true;
                    continue;
                }
            }

            if (!exists) {
                WebsNLists[WebUrl].push(_spPageContextInfo.pageListId.toUpperCase());
                _self.ListsCount++;
            }
        }

        _self.PageLists = WebsNLists;
        WebsNLists = null;

    };


    function clientContextError(sender, args) {
        console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    }

    ;


    this.MakeRequest = function () {
        var webs = [];
        var ctx = SP.ClientContext.get_current();
        var site = ctx.get_site();
        ctx.load(site);
        var i = 0;
        for (var weburl in _self.PageLists) {
            var url = "";
            if (weburl != "/")
                url = weburl;

            var listsn = _self.PageLists[weburl];
            webs[i] = {};
            webs[i].Web = site.openWeb(url);
            webs[i].lists = [];
            webs[i].views = [];
            ctx.load(webs[i].Web);

            for (var j = 0; j < listsn.length; j++) {
                //console.log(listsn[j]);
                webs[i].lists[j] = webs[i].Web.get_lists().getById(listsn[j]);
                webs[i].views[j] = webs[i].lists[j].get_views();

                ctx.load(webs[i].lists[j]);
                ctx.load(webs[i].lists[j], 'EffectiveBasePermissions');
                ctx.load(webs[i].views[j]);
            }

            i++;
        }

        ctx.executeQueryAsync(
            function (data) {
                var EditBlock = "";

                for (var i = 0; i < webs.length; i++) {

                    for (var j = 0; j < webs[i].lists.length; j++) {

                        var targetList = webs[i].lists[j];

                        var permission = targetList.get_effectiveBasePermissions();
                        if (permission.has(SP.PermissionKind.addListItems)) {
                            var viewsEnumerator = webs[i].views[j].getEnumerator();
                            var viewInfo = "";
                            while (viewsEnumerator.moveNext()) {
                                var view = viewsEnumerator.get_current();
                                if (view.get_defaultView()) {
                                    var litemplate = "<li class=\"static edit\"><a class=\"static menu-item ms-core-listMenu-item ms-displayInline ms-navedit-linkNode\" href=\"{0}\"><span class=\"additional-background ms-navedit-flyoutArrow\"><span class=\"menu-item-text\">{1}</span></span></a></li>";
                                    EditBlock += String.format(litemplate, view.get_serverRelativeUrl(), targetList.get_title());
                                }
                            }

                        }
                    }
                }

                if (EditBlock) {
                    var EditMenu = String.format("<div class=\"ms-core-listMenu-verticalBox\"><span>Управление списками</span><ul class=\"root ms-core-listMenu-root static\">{0}</ul></div>", EditBlock);

                    var leftmenu = document.getElementById(DOMElementId);
                    if (leftmenu) {
                        var newdiv = document.createElement('div');
                        newdiv.setAttribute('id', 'EditListDiv');
                        newdiv.innerHTML = EditMenu;
                        leftmenu.appendChild(newdiv);
                    }
                }

            },
            clientContextError
        );
    };


    function _Init() {
        ExecuteOrDelayUntilScriptLoaded(function () {
            FillPageLists();

            _self.MakeRequest();

        }, 'sp.js');
    }

    _Init();

};


(function () {
    function init() {
        new CIB.EditMenu();
    }

    if (_spBodyOnLoadCalled) {
        init();
    } else {
        _spBodyOnLoadFunctions.push(init);
    }

})();
